#include "string.h"
#include "Queue.h"

qQueue* QueueCreate(int datasize, int datalen)
{
    int ret = 0;
    qQueue* queue;
    queue = (qQueue*)malloc(sizeof(qQueue));
    if (!queue)
        return NULL;
    queue->count = (datalen + 1) * datasize;
    queue->datasize = datasize;
    ret = QueueInit(queue);
    if (ret)
    {
        return queue;
    }
    else
    {
        free(queue);
        return NULL;
    }
    return NULL;
}

int QueueInit(qQueue* queue)
{
    queue->front = queue->rear = 0;
    queue->data = (char*)malloc(sizeof(char) * queue->count);
    if (!queue->data)
        return -1;
    return 1;
}

int CopyDataToQueue(qQueue* queue, void* data, int size, int position)
{
    char* buf = (char*)data;
    char* qData = queue->data;
    if (position == SEND_TO_BACK)
    {
        if (QueueIsFull(queue))
        {
            memcpy(&qData[queue->rear], buf, size);
            queue->rear = (queue->rear + size) % queue->count;
        }
        else {
            DEBUG_PRINTF("full\n");
            return 1;
        }
    }
    else
    {
        if (QueueIsEmpty(queue))
        {
            memcpy(buf, &qData[queue->front], size);
            queue->front = (queue->front + size) % queue->count;
        }
        else
        {
            DEBUG_PRINTF("empty\n");
            return 1;
        }
    }
    //DEBUG_PRINTF("front = %d,rear = %d\n", queue->front, queue->rear);
    return 0;
}

int PushDataToQueue(qQueue* queue, void* data)
{
    return CopyDataToQueue(queue, data, queue->datasize, SEND_TO_BACK);
}

int PopDataToQueue(qQueue* queue, void* data)
{
    return CopyDataToQueue(queue, data, queue->datasize, SEND_TO_FRONT);
}


int QueueIsFull(qQueue* queue)
{
    if (queue->front == ((queue->rear + queue->datasize) % queue->count))
    {
        DEBUG_PRINTF("is full ");
        return 0;
    }
    else {
        return 1;
    }
}


int QueueIsEmpty(qQueue* queue)
{
    if ((queue->rear == queue->front))
    {
        return 0;
    }
    else {
        return 1;
    }
}
